package com.lock;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author:wesley
 */
public class LockWatch implements Watcher {

    private DistributedLock distributedLock;

    private DoServiceTemplate doServiceTemplate;

    private Logger logger = LoggerFactory.getLogger(LockWatch.class);


    public LockWatch(DistributedLock distributedLock, DoServiceTemplate doServiceTemplate) {
        this.distributedLock = distributedLock;
        this.doServiceTemplate = doServiceTemplate;
    }

    public void process(WatchedEvent watchedEvent) {

        /**
         *这是等待的路径删除了 ，那么该轮到下一个人
         *
         * 本身可能是 0000048,前面一个人是00000047
         * 执行完毕之后，那么就把47这个节点删除 ，那么就应该是47出去,
         *
         * 如果这个节点是第一个或者最后一个，那么不能进来了。
         * 第一个节点不能触发时间
         * 最后一个节点没有waitPath
         *
         *
         */
        if (watchedEvent.getType() == Event.EventType.NodeDeleted &&
                watchedEvent.getPath().equals(distributedLock.getWaitPath())) {


            logger.info(Thread.currentThread().getName()+"收到消息，前面人挂了，该我出去了....");

            try {
                if (distributedLock.checkMinPath()) {
                    doSometime("is process");
                    distributedLock.unlock();
                }
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public void doSometime(String msg){
        logger.info("获取锁成功。。。。马上干活了！"+msg);
        doServiceTemplate.doService();
        LockMainTest.countDownLatch.countDown();
    }


}
